/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yunhoo.asset.bean;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.yunhoo.asset.db.impl.AssetSqlImpl;
import com.yunhoo.asset.model.Asset;
import com.yunhoo.asset.model.AssetExtend;
import com.yunhoo.base.model.Person;
import com.yunhoo.sys.db.util.IbatisTemplate;
import com.yunhoo.sys.util.common.LoginParam;
import com.yunhoo.sys.util.common.Null;
import com.yunhoo.sys.util.common.ToolKit;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem; 
 
@ManagedBean(name = "buidAssetFromProcure")
@SessionScoped
public class BuidAssetFromProcure {

    private final String NAMESPACE = "psncard.";
    private Asset asset = null;
    
    private DataModel<AssetExtend> cateModel = new ListDataModel<AssetExtend>();//采购执行列表,用于生产资产的参照
    private List<Asset> assetFromProcure = null;//采购生成资产；

    public BuidAssetFromProcure() {
        initCateli();
    } 
    
    public void deptChange() {
        AssetExtend asst = cateModel.getRowData();
        if (asst.isSelected()) {
            String dcode = asst.getDeptCode();
            System.out.println("deptCode " + dcode);    
            
            if(asst.getPersonSelectli() != null) return;
            
            List<Person> personlist = getPersonList(dcode);
            if (personlist != null && personlist.size() > 0) {
                
                asst.setPersonSelectli(new ArrayList<SelectItem>());
                
                List<SelectItem> perSelectli = asst.getPersonSelectli();
                for (Person p : personlist) {
                    perSelectli.add(new SelectItem(p.getCpsn_number(), p.getCpsn_name()));
                }
            }
        }
    }
  
    private void initCateli() {
        System.out.println("initCateli !");
        Map map = new HashMap();
        map.put("orgCode", LoginParam.getOrg().getCode());
        map.put("iyear", LoginParam.getIyear());
        List<AssetExtend> cateli = IbatisTemplate.queryForList(NAMESPACE + "queryCategroyForAsset", map);
        cateModel.setWrappedData(cateli);
        System.out.println("cateli : " + cateli.size());
    }

    public void buildFromProcure() {//由采购生成资产
        String orgCode = LoginParam.getOrg().getCode();
        Integer maxAssetCode = (Integer) IbatisTemplate.query(NAMESPACE + "queryMaxAssetCode", orgCode);
        System.out.println("maxAssetCode : " + maxAssetCode);
        assetFromProcure = new ArrayList<Asset>();
        for (AssetExtend cate : cateModel) {
            if (cate.isSelected()) {
                for (int i = 0; i < cate.getCount(); i++) {
                    maxAssetCode++;
                    Asset ast = new Asset();
                    ast.setOrgCode(orgCode);
                    ast.setAssetCode(String.valueOf(maxAssetCode));
                    ast.setAssetName(cate.getCateName());
                    ast.setModel(cate.getModel());
                    ast.setBrand(cate.getBrand());
                    ast.setManufacture(cate.getManufacture());
                    ast.setPurchDate(cate.getPurchDate());
                    ast.setShelfLife(cate.getShelfLife());
                    ast.getDept().setCode(cate.getDeptCode());
                    ast.getPerson().setCpsn_number(Null.convert(cate.getPerson().getCpsn_number()));
                    ast.getPerson().setCpsn_name(Null.convert(cate.getPerson().getCpsn_name()));
                    ast.getKeeper().setCpsn_number("");
                    ast.getKeeper().setCpsn_name("");
                    ast.setUseStatus(cate.getUseStatus());
                    ast.setPrice(cate.getPrice());
                    ast.setMemo(cate.getMemo());
                    ast.setFromProcure(1);
                    assetFromProcure.add(ast);
                }
            }
        }
    }

    public void saveAssetFromProcure() {
            if (assetFromProcure == null || assetFromProcure.isEmpty()) {
                return;
            }
            boolean ok = true;
        SqlMapClient client = IbatisTemplate.getSqlMapClient();
        try {
            client.startTransaction();
            client.startBatch();
            
            for(Asset data:assetFromProcure){
                client.insert(NAMESPACE + "insertAsset",data);
            }
            
            
            for (AssetExtend cate : cateModel) {
                if (cate.isSelected()) {
                    client.update("psncard.updateExecDetail_toAsset",cate.getId());
                }
            }
            
            client.executeBatch();
            client.commitTransaction();       
        } catch (SQLException ex) {
            ok = false;
                try {
                    client.endTransaction();
                } catch (SQLException ex1) {
                    Logger.getLogger(BuidAssetFromProcure.class.getName()).log(Level.SEVERE, null, ex1);
                }
            Logger.getLogger(BuidAssetFromProcure.class.getName()).log(Level.SEVERE, null, ex);
        }     
        if(ok){
            assetFromProcure = null;
            initCateli();
           ToolKit.msgs_info(FacesContext.getCurrentInstance(), null, "已生成资产！");
        }else{
           ToolKit.msgs_err(FacesContext.getCurrentInstance(), null, "生成失败！");
        }
    }
    
    public void assetEditRowSelected(Integer rowKey){
        System.out.println("rowdblclick : " + rowKey);
        asset = assetFromProcure.get(rowKey);
    }
    
    public void keeperSelected(String keeperCode,String keeperName){
        System.out.println("keeperSelected : " + keeperCode + " -- " + keeperName);
        asset.getKeeper().setCpsn_number(keeperCode);
        asset.getKeeper().setCpsn_name(keeperName);
    }
    
    
    
    public void userSelected(String userCode,String userName){
        System.out.println("userSelected : " + userCode + " -- " + userName);
        asset.getPerson().setCpsn_number(userCode);
        asset.getPerson().setCpsn_name(userName);
    }
    
    
    
    private List<Person> getPersonList(String deptCode) {
        Person param = new Person();
        param.setOrgCode(LoginParam.getOrg().getCode());
        param.setIyear(LoginParam.getIyear());
        param.setDeptCode(deptCode);
        return IbatisTemplate.queryForList("person.queryListByDept", param);
    }
 

    public String maxCode() {
        String orgCode = LoginParam.getOrg().getCode();
        Integer maxCode = (Integer) IbatisTemplate.query(NAMESPACE + "queryMaxAssetCode", orgCode);
        if (maxCode == null) {
            maxCode = 0;
        }
        return String.format("%08d%n", maxCode + 1).trim();
    }

    public Asset getAsset() {
        return asset;
    }

    public void setAsset(Asset asset) {
        this.asset = asset;
    }

    public DataModel<AssetExtend> getCateModel() {
        return cateModel;
    }

    public void setCateModel(DataModel<AssetExtend> cateModel) {
        this.cateModel = cateModel;
    }

    public List<Asset> getAssetFromProcure() {
        return assetFromProcure;
    }

    public void setAssetFromProcure(List<Asset> assetFromProcure) {
        this.assetFromProcure = assetFromProcure;
    }
}
